// Simple Client.cpp
//
// modified by Brian Schick.
// 4/29/2010 - to clean up properly.

#include <stdio.h>      /* for printf(), fprintf() */
#include <Winsock2.h>    /* for socket(),... */
#include <stdlib.h>     /* for exit() */

#define SENDBUFSIZE 128   /* Size of receive buffer */

#define MYMESG			"goodbye cruel world"
#define SRVR_ADDRESS	"127.0.0.1"
#define SRVR_PORT		7654

void CloseGracefully( SOCKET s )
{
	// shutdown socket
	// close socket
	if ( s != INVALID_SOCKET )
	{
		if ( shutdown(s,SD_BOTH) == SOCKET_ERROR )
			printf("Socket shutdown failed with error: %d\n", WSAGetLastError() );
		if ( closesocket(s) == SOCKET_ERROR )
			printf("Socket closesocket failed with error: %d\n", WSAGetLastError() );
	}
	// cleanup WSA
	if ( WSACleanup() == SOCKET_ERROR )
		printf("WSA Cleanup failed with error: %d\n", WSAGetLastError() );
}

void DieWithError(SOCKET s, char *errorMessage)
{
	fprintf(stderr, "%s: %d\n", errorMessage, WSAGetLastError());
	CloseGracefully( s );
}

void main(int argc, char *argv[])
{
    SOCKET srvrSock = SOCKET_ERROR;                    /* Socket descriptor for server */
    struct sockaddr_in srvrAddr; /* Local address */
    int clntLen = 0;            /* Length of client address data structure */
    WSADATA wsaData;                 /* Structure for WinSock setup communication */
	char sendbuf[SENDBUFSIZE];        /* Buffer for echo string */
	int send_len;                    /* Size of received message */
	int msgsize;
	int portnum = SRVR_PORT;

    if (argc ==  2) 
	{
		// argv[1] == the optional port number
		portnum = atoi(argv[1]);
	}

    if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) /* Load Winsock 2.0 DLL */
    {
        fprintf(stderr, "WSAStartup() failed\n");
		CloseGracefully( srvrSock );
        exit(1);
    }

    // Create socket for incoming connections/
    srvrSock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	// if socket fails, it returns INVALID_SOCKET
	if (srvrSock == INVALID_SOCKET)
	{
		printf("Error: socket() failed with err number %d\n", WSAGetLastError());
		DieWithError(srvrSock,"socket(...) failed");
		exit(1);
	}

    // Construct local address structure
    memset(&srvrAddr, 0, sizeof(srvrAddr));   /* Zero out structure */
    srvrAddr.sin_family = AF_INET;                /* Internet address family */
    srvrAddr.sin_addr.s_addr = inet_addr(SRVR_ADDRESS); /* Any incoming interface */
    srvrAddr.sin_port = htons(portnum);      /* Dest port */

	// Send message to 
	strcpy(sendbuf, MYMESG);

	send_len = sendto(srvrSock,
					sendbuf,
					strlen(sendbuf) + 1,
					0,
					(SOCKADDR *) &srvrAddr,
					sizeof(srvrAddr)
				);

	if ( send_len == SOCKET_ERROR )
	{
		printf("Send message failed\n");
	}
	else
	{
		printf("Sent %d of %d bytes to %s:%u\n", send_len, strlen(sendbuf) + 1, SRVR_ADDRESS, SRVR_PORT);
	}

	// When done, close socket
	CloseGracefully( srvrSock );
}
